<template>
  <div>
    <div class="query-form">
      <a-form ref="queryFormRef" :model="queryForm" layout="inline" @submit="handleQuery">
        <a-form-item field="deptName" label="部门名称">
          <a-input v-model="queryForm.deptName" placeholder="请输入部门名称" />
        </a-form-item>
        <a-form-item class="operate">
          <a-button type="primary" html-type="submit">查询</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <div class="operate-wrapper">
      <a-button type="primary" status="success" @click="openAddModal">添加</a-button>
    </div>
    <a-table :data="tableData" row-key="_id">
      <template #columns>
        <a-table-column title="部门名称" data-index="deptName"></a-table-column>
        <a-table-column title="负责人" data-index="userName"></a-table-column>
        <a-table-column title="更新时间" data-index="updateTime"></a-table-column>
        <a-table-column title="创建时间" data-index="createTime"></a-table-column>
        <a-table-column title="操作">
          <template #cell="{ record }">
            <a-button
              v-if="record.userName != 'superAdmin'"
              type="text"
              @click="openUptModal(record)"
            >编辑</a-button>
            <a-button
              v-if="record.userName != 'superAdmin'"
              type="text"
              @click="handleDelete(record)"
            >删除</a-button>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <!-- 添加/编辑弹窗 -->
    <a-modal :visible="modalVisible" title="添加/编辑部门" @ok="confirmModal" @cancel="closeModal">
      <a-form ref="modalFormRef" :model="modalForm" :rules="modalFormRules">
        <a-form-item field="parentId" label="上级部门">
          <a-cascader
            v-model="modalForm.parentId"
            :field-names="fieldNames"
            :options="tableData"
            placeholder="请选择上级部门"
            check-strictly
          />
        </a-form-item>
        <a-form-item field="deptName" label="部门名称">
          <a-input v-model="modalForm.deptName" placeholder="请输入部门名称" />
        </a-form-item>
        <a-form-item field="userName" label="负责人">
          <a-select
            v-model="modalForm.userName"
            :show-extra-options="false"
            placeholder="请选择部门负责人"
            @change="selectChange"
          >
            <a-option
              v-for="(item,index) in userOptions"
              :key="index"
              :label="item.userName"
              :value="`${item._id}/${item.userName}/${item.userEmail}`"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="userEmail" label="负责人邮箱">
          <a-input v-model="modalForm.userEmail" disabled />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from "vue";
import { deptAdd, deptDelete, deptUpdate, deptList } from "@/api/dept/index.js";
import { userAllList } from "@/api/user/index.js";
import { Modal } from "@arco-design/web-vue";

export default {
  setup() {
    onMounted(() => {
      getDeptList();
      getAllUserList();
    });
    //   条件查询
    const queryFormRef = ref(null);
    const queryForm = reactive({
      deptName: ""
    });

    // 重置
    const handleReset = () => {
      queryFormRef.value.resetFields();
      getDeptList();
    };

    // 查询
    const handleQuery = () => {
      getDeptList();
    };

    // 打开添加弹窗
    const modalVisible = ref(false);
    const modalFormRef = ref(null);
    const action = ref("add");
    const fieldNames = { value: "_id", label: "deptName" };
    const openAddModal = () => {
      action.value = "add";
      modalFormRef.value.resetFields();
      modalVisible.value = true;
    };

    // 弹窗表单
    const modalForm = reactive({
      parentId: [null],
      deptName: "",
      userName: "",
      userEmail: ""
    });

    const modalFormRules = reactive({
      parentId: { required: true, message: "parentId is required" },
      deptName: { required: true, message: "deptName is required" },
      userName: { required: true, message: "userName is required" }
    });

    // 弹窗确定和取消
    const confirmModal = () => {
      modalFormRef.value.validate(async (errors, Record) => {
        if (errors) return;
        if (action.value == "add") {
          const { data } = await deptAdd(modalForm);
          console.log("data", data);
        }
        if (action.value == "upt") {
          const { data } = await deptUpdate(modalForm);
          console.log("data", data);
        }
        getDeptList();
        modalVisible.value = false;
      });
    };

    const closeModal = () => {
      modalVisible.value = false;
      modalFormRef.value.resetFields();
    };

    // 表格数据
    const tableData = ref([]);
    const getDeptList = async () => {
      const { data } = await deptList(queryForm);
      tableData.value = data.data;
    };

    // 用户列表
    const userOptions = ref([]);
    const getAllUserList = async () => {
      const { data } = await userAllList();
      console.log(data);
      userOptions.value = data.data;
    };
    const selectChange = val => {
      const [_id, userName, userEmail] = val.split("/");
      Object.assign(modalForm, { userId: _id, userName, userEmail });
    };

    // 编辑
    const openUptModal = record => {
      action.value = "upt";
      Object.assign(modalForm, record);
      modalVisible.value = true;
    };

    // 删除
    const handleDelete = record => {
      Modal.warning({
        title: "警告",
        content: "此操作将停用该部门，是否继续！",
        hideCancel: false,
        onOk: async () => {
          const { data } = await deptDelete({
            _id: record._id
          });
          console.log(data);
          getDeptList();
        }
      });
    };
    return {
      queryFormRef,
      queryForm,
      handleReset,
      handleQuery,
      action,
      modalFormRef,
      openAddModal,
      modalForm,
      modalFormRules,
      fieldNames,
      modalVisible,
      confirmModal,
      closeModal,
      tableData,
      openUptModal,
      handleDelete,
      getDeptList,
      getAllUserList,
      userOptions,
      selectChange
    };
  }
};
</script>

<style>
</style>